<template>
  <div class="learning-center">
    <el-row :gutter="20">
      <el-col :span="16">
        <!-- 已报名赛事 -->
        <el-card class="enrolled-competition">
          <template #header>
            <div class="card-header">
              <span>已报名赛事</span>
              <el-button type="primary" @click="goToWeeklyReport">周报</el-button>
            </div>
          </template>
          <div v-if="enrolledCompetition" class="competition-info">
            <h3>{{ enrolledCompetition.name }}</h3>
            <div class="info-row">
              <span>比赛时间：{{ enrolledCompetition.time }}</span>
            </div>
            <div class="info-row">
              <span>比赛地点：{{ enrolledCompetition.location }}</span>
            </div>
            <!-- 只有在有报名赛事时才显示学习进度 -->
            <el-card v-if="knowledgePoints" class="learning-progress mt-4">
              <template #header>
                <div class="card-header">
                  <span>{{ enrolledCompetition.name }} - 学习进度</span>
                </div>
              </template>
              <MindMap
                :data="knowledgePoints"
                @update="handleKnowledgePointUpdate"
              />
            </el-card>
          </div>
          <div v-else class="empty-state">
            <el-empty description="暂无报名赛事" />
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <!-- 日历组件 -->
        <el-card class="calendar-card">
          <el-calendar v-model="currentDate">
            <template #header>
              <div class="calendar-header">
                <div class="calendar-title">{{ currentYear }}年{{ currentMonth }}月</div>
                <div class="calendar-controls">
                  <el-button-group>
                    <el-button size="small" @click="selectPrevMonth">上月</el-button>
                    <el-button size="small" @click="selectCurrentMonth">今天</el-button>
                    <el-button size="small" @click="selectNextMonth">下月</el-button>
                  </el-button-group>
                </div>
              </div>
            </template>
            <template #dateCell="{ data }">
              <div class="calendar-cell" :class="{ 'current-day': isCurrentDay(data.day) }">
                <span class="date-number">{{ data.day.split('-').slice(-1)[0] }}</span>
              </div>
            </template>
          </el-calendar>
        </el-card>

        <!-- 打卡组件 -->
        <el-card class="check-in mt-4">
          <template #header>
            <div class="card-header">
              <span>每日打卡</span>
            </div>
          </template>
          <div class="check-in-content">
            <p>已连续打卡 {{ checkInStreak }} 天</p>
            <el-button 
              type="primary" 
              :disabled="todayChecked"
              @click="handleCheckIn"
            >
              {{ todayChecked ? '今日已打卡' : '立即打卡' }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import MindMap from '../components/MindMap.vue'
import { 
  getEnrolledCompetition,
  getCheckInRecords,
  checkIn,
  updateKnowledgePoint
} from '../api/learning'
import { ElMessage } from 'element-plus'

const router = useRouter()
const currentDate = ref(new Date())

// 计算当前年月
const currentYear = computed(() => currentDate.value.getFullYear())
const currentMonth = computed(() => currentDate.value.getMonth() + 1)

const enrolledCompetition = ref({})
const knowledgePoints = ref(null)
const checkInRecords = ref({})
const checkInStreak = ref(0)
const todayChecked = ref(false)

// 日期控制
const selectPrevMonth = () => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() - 1)
  currentDate.value = newDate
}

const selectNextMonth = () => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() + 1)
  currentDate.value = newDate
}

const selectCurrentMonth = () => {
  currentDate.value = new Date()
}

// 检查是否是当前日期
const isCurrentDay = (dateStr) => {
  const today = new Date()
  const date = new Date(dateStr)
  return date.toDateString() === today.toDateString()
}


// 获取已报名赛事
const fetchEnrolledCompetition = async () => {
  try {
    const { data } = await getEnrolledCompetition()
    enrolledCompetition.value = data
    // 设置知识点数据
    knowledgePoints.value = data.knowledgePoints
  } catch (error) {
    console.error('获取已报名赛事失败:', error)
    ElMessage.error('获取已报名赛事失败')
  }
}

// 处理知识点更新
const handleKnowledgePointUpdate = async (data) => {
  try {
    const { data: updatedPoints } = await updateKnowledgePoint(data)
    // 更新知识点数据
    knowledgePoints.value = updatedPoints
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新知识点状态失败:', error)
    ElMessage.error('更新知识点状态失败')
  }
}

// 获取打卡记录
const fetchCheckInRecords = async () => {
  try {
    const { data } = await getCheckInRecords()
    checkInRecords.value = data.records
    checkInStreak.value = data.streak
    todayChecked.value = data.todayChecked
  } catch (error) {
    console.error('获取打卡记录失败:', error)
    ElMessage.error('获取打卡记录失败')
  }
}

// 处理打卡
const handleCheckIn = async () => {
  try {
    const { data } = await checkIn()
    // 更新打卡状态
    checkInRecords.value = data.records
    checkInStreak.value = data.streak
    todayChecked.value = true
    ElMessage.success('打卡成功')
  } catch (error) {
    console.error('打卡失败:', error)
    ElMessage.error('打卡失败')
  }
}

// 跳转到周报页面
const goToWeeklyReport = () => {
  router.push('/weekly-report')
}

onMounted(() => {
  fetchEnrolledCompetition()
  fetchCheckInRecords()
})
</script>

<style scoped>
.learning-center {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.enrolled-competition {
  margin-bottom: 20px;
}

.competition-info {
  h3 {
    margin: 0 0 16px;
    font-size: 18px;
    color: #303133;
  }
}

.info-row {
  margin-bottom: 12px;
  color: #606266;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.mt-4 {
  margin-top: 16px;
}

.learning-progress {
  margin-top: 24px;
  
  :deep(.el-card__body) {
    padding: 0;
    overflow-x: auto;
  }
}

.empty-state {
  padding: 32px 0;
}

/* 日历样式 */
.calendar-card {
  :deep(.el-calendar) {
    background: none;
  }

  :deep(.el-calendar__header) {
    padding: 0;
  }

  :deep(.el-calendar__body) {
    padding: 4px 0 0;
  }

  :deep(.el-calendar-table) {
    thead th {
      text-align: center;
      padding: 2px 0;
      font-size: 12px;
      color: #606266;
      border-bottom: 1px solid #EBEEF5;
    }

    td {
      border: none;
      text-align: center;
      padding: 0;
    }
  }

  :deep(.el-calendar-day) {
    height: 60px;
    padding: 1px;
    box-sizing: border-box;
  }

  :deep(.el-button--small) {
    padding: 4px 8px;
    font-size: 12px;
  }

  :deep(.el-button-group) {
    .el-button {
      margin-left: -1px;
    }
    .el-button:first-child {
      margin-left: 0;
    }
  }
}

.calendar-header {
  padding: 4px 8px;
  border-bottom: 1px solid #ebeef5;
}

.calendar-title {
  font-size: 13px;
  font-weight: 500;
  text-align: center;
  margin-bottom: 4px;
}

.calendar-controls {
  display: flex;
  justify-content: center;
  align-items: center;
}

.calendar-cell {
  position: relative;
  height: 100%;
  min-height: 50px;
  padding: 2px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.date-number {
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 1px;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
}

.current-day .date-number {
  background-color: #409EFF;
  color: white;
  border-radius: 50%;
}

.competition-mark {
  font-size: 10px;
  color: #409EFF;
  margin-top: 1px;
  text-align: center;
  padding: 0 2px;
  background-color: #ecf5ff;
  border-radius: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 90%;
}

.check-in-mark {
  position: absolute;
  bottom: 1px;
  left: 50%;
  transform: translateX(-50%);
  width: 3px;
  height: 3px;
  border-radius: 50%;
  background-color: #67C23A;
}

:deep(.prev-month),
:deep(.next-month) {
  .date-number {
    opacity: 0.3;
  }
  .calendar-cell {
    color: #C0C4CC;
  }
}

.check-in-content {
  text-align: center;
}

.check-in-content p {
  margin-bottom: 15px;
}
</style>
